vue3 typescript 在methods和setup中使用$refs并解决Object is possibly 'null'

您所在的位置:网站首页 vue3 methods this vue3 typescript 在methods和setup中使用$refs并解决Object is possibly 'null'

vue3 typescript 在methods和setup中使用$refs并解决Object is possibly 'null'

#vue3 typescript 在methods和setup中使用$refs并解决Object is possibly 'null'| 来源: 网络整理| 查看: 265

    在vue中,通常在template中给某组件设置了 ref属性后,在methods中,直接this.$refs调用即可。

    但是使用了typescript后,this.$refs.xxx将会被提示Object is of type 'unknown'。这需要将变量定义一下类型。

import  XXComponent  from 'XXComponent.vue'; ... (this.$refs.xxx as XXComponent).method import { XXComponent } from 'XXComponent'; ... (this.$refs.xxx as typeof XXComponent).method

    然后在setup中是没有this使用的,官方文档中写到使用的例子

  This is a root element   import { ref, onMounted } from 'vue'   export default {     setup() {       const root = ref(null)       onMounted(() => {         // the DOM element will be assigned to the ref after initial render         console.log(root.value) // This is a root element       })       return {         root       }     }   }

    然而,直接复制官方的例子后,在setup中想使用组件的方法,root.value.xxx提示Object is possibly 'null'。methods中使用setup导出的root.xxx也提示Object is possibly 'null'。需要定义一下这个root的类型

import {onMounted} from 'vue'; ... interface IComponent{     xxx?:Function } ... setup(){ const root = ref({}); onMounted(() => {             console.log(root.value.xxx)          //执行         root.value.xxx(params);                }) }, methods:{     YYY(){         console.log(root.xxx);         //执行         root.xxx(params);     } }

    只在methods中使用就是对每个$refs的属性对象都需要转换类型判断,如果是组件就需要import组件。

    在setup中定义共享出去就需要定义每一个使用到的ref。

    以上全是笨办法,应该有其他更简洁的方法。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3